<template>
    <div class='warning_warp '>
        <div class="time_set">
            <el-button @click='selectList' type="primary">选择设备---{{this.nowshebei}}</el-button>
               <el-date-picker v-model="bdate" type="datetime"  value-format="timestamp" placeholder="选择日期时间" :picker-options="pickerOptionsStart" style="margin-right: 10px;">
                </el-date-picker>
                至
                <el-date-picker v-model="edate" type="datetime" value-format="timestamp" placeholder="选择日期时间" :picker-options="pickerOptionsEnd" style="margin-left: 10px;">
                </el-date-picker>
            <el-button @click='search' type="primary">搜索</el-button>
            <span style="float:right;" v-if="this.count !== 0 && this.count!=''">共查询出 {{count}} 条数据 
                <el-button type="primary" @click="daochu2()">全部导出</el-button>
            </span>
        </div>
        <div class="table_wrap op table border" style="margin-top:20px;">
            <el-table height="670px" :row-style="getRowClass" :cell-style="getRowClass" :header-row-style="getRowClass"
                :header-cell-style="getRowClass" :data="tableData" style="width: 100%">
                <el-table-column type="index" label="序列号" width="70" header-align="center" align="center">
                </el-table-column>
                <el-table-column prop="devname" label="设备名称" width="">
                </el-table-column>
                <el-table-column prop="idname" label="单项名称" width="">
                </el-table-column>
                <el-table-column prop="triggertime" label="触发时间" width="">
                </el-table-column>
                <el-table-column prop="triggerinfo" label="报警信息">
                </el-table-column>
                <el-table-column prop="recoverinfo" label="恢复方式">
                </el-table-column>
                <el-table-column prop="recovertime" label="恢复时间" width="">
                </el-table-column>
                <el-table-column prop="alarmvalue" label="报警值" width="150" header-align="center" align="center">
                </el-table-column>
                <el-table-column prop="ahhvalue" label="高高限" width="120" header-align="center" align="center">
                </el-table-column>
                <el-table-column prop="allvalue" label="低低限" width="120" header-align="center" align="center">
                </el-table-column>
                <el-table-column prop="alarmlimit" label="报警级别" width="100" header-align="center" align="center">
                </el-table-column>
            </el-table>

            <div class="page_wrap">
                <!-- <el-pagination @current-change="handleCurrentChange" background layout="prev, pager, next"
                    :page-size="size" :total="count">
                </el-pagination> -->
                <span>一共{{ this.count }}条</span>
                <button class="yema" @click="prevPage" :disabled="currentPage === 1"><</button>
                <span v-for="(page, index) in displayedPages" :key="index">
                <button class="yema" :class="{ active: currentPage === page }" @click="gotoPage(page)">
                    {{ page }}
                </button>
                </span>
                <button class="yema" @click="nextPage" :disabled="currentPage === totalPages">></button>
                <input class="yema_input" ref="inputRef" type="number" v-model="inputPage" @input="adjustInputWidth" />
                <button class="yema"  @click="gotoPage(inputPage)">
                    跳转
                </button>
            </div>
        </div>
        <el-dialog
            title="设备选择"
            :visible.sync="dialogVisible"
            width="50%"
            :append-to-body="true"
            :before-close="handleClose">
            <div>
                <div class="warnhis_type">
                    <div class="warnhis_type_flex" >
                        <div class="warnhis_type_but" @click="selectType('all')">
                            <div :class="this.nowshebei == '不限制设备' ? 'warnhis_type_active':'warnhis_type_nomal'">
                                不限制设备
                            </div>
                            
                        </div>
                        <div class="warnhis_type_but" v-for="(item,index) in this.list" :key="index" @click="selectType(item)">
                            <div :class="item.active == 1 ? 'warnhis_type_active':'warnhis_type_nomal'">
                                {{item.typename}}
                            </div>
                            
                        </div>
                    </div>
                </div>
                <div class="warnhis_line"></div>
                <div class="warnhis_shebei">
                    <div class="warnhis_type_flex">
                        <div class="warnhis_type_but" v-for="(item2,index2) in this.specific" :key="index2" @click="selectTypelink(item2)">
                            <div class="warnhis_type_nomal">
                                {{item2.name}}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                bdate:'',
                edate:this.getCurrentTimestampInSeconds(),
                date: '',
                nowselect:{},
                nowshebei:'不限制设备',
                list:[],
                specific:[],
                tableData: [],
                size: 100,
                count:0,//共查询数据数量
                currentPage: 0,//当前页码从1开始
                totalPages: 0,//总页码
                inputPage: 0,//跳转页码默认值
                dialogVisible: false,
                page:0,//下发页码从0开始
                daochuArr:[
                ],
                
                pickerOptionsStart: {
                    disabledDate: time => {
                        let endDateVal = this.edate;
                        if (endDateVal) {
                            return time.getTime() > new Date(endDateVal).getTime();
                        }
                        return time.getTime() < new Date(endDateVal).getTime() - 8.64e7;
                    }
                },
                pickerOptionsEnd: {
                    disabledDate: time => {
                        let beginDateVal = this.bdate;
                        if (beginDateVal) {
                            return (
                                time.getTime() <
                                new Date(beginDateVal).getTime()
                            );
                        }
                    },
                },
            }
        },
        created() {
            this.getlist()
            // 假数据
            // this.count = 401
            // this.totalPages = Math.ceil(this.count/this.size) 
        },
        computed: {
            afterBetime(){
                return this.bdate === 0 ? 0 :this.bdate/1000
            },
            afterEtime(){
                console.log(this.edate)
                return this.edate === 0 ? 0 :this.edate/1000
            },
            displayedPages() {
                const center = this.currentPage;
                const pagesToShow = 3; // 包括中心页在内总共显示3个页码
                let start = Math.max(1, center - Math.floor(pagesToShow / 2));
                let end = Math.min(this.totalPages, start + pagesToShow - 1);
                if (end - start + 1 < pagesToShow) {
                    start = Math.max(1, end - pagesToShow + 1);
                }
                return Array.from({ length: end - start + 1 }, (_, i) => start + i);
            },
        },
        methods: {
            gotoPage(page) {
                this.currentPage = parseInt(page);
                this.inputPage = this.currentPage;
                this.page = this.currentPage -1
                this.getData()
            },
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.page = this.currentPage -1
                    this.getData()
                }
            },
            nextPage() {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.page = this.currentPage -1
                    this.getData()
                }
            },
            adjustInputWidth() {
                const inputElement = this.$refs.inputRef;
                inputElement.style.width = '70px'; // 重置宽度
                if(this.inputPage.length >= 6){
                    inputElement.style.width = (70+(8*(this.inputPage.length-6))).toString()+'px'; // 设置宽度
                }else{
                    inputElement.style.width = '70px'; // 重置宽度
                }
                // inputElement.style.width = `${inputElement.scrollWidth}px`; // 设置宽度
            },
            getCurrentTimestampInSeconds() {
                const now = new Date();
                const year = now.getFullYear();
                const month = now.getMonth() + 1; // 注意月份是从0开始的
                const day = now.getDate();
                const hours = now.getHours();
                const minutes = now.getMinutes();
                const seconds = now.getSeconds();

                return new Date(year, month - 1, day, hours, minutes, seconds).getTime();
            },
            getlist(){
                var params = {
                    "getdevlink":"",
                    [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
                }
                this.$http.post(this.$baseUrl, params).then((res) => {
                    this.list = []
                    if(res.data.result == 'ok'){
                        var data = res.data.getdevlink
                        for(var i = 0; i < data.length; i++){
                            var s = 0
                            if(data[i].type != 31 && data[i].type != 32){//屏蔽掉31 32无线网关模块设备
                                for(var y = 0; y < data[i].devlink.length; y++){
                                    if(data[i].devlink[y].ready == 1){
                                        s++
                                    }
                                }
                                if(s > 0){
                                    var arr = {
                                        devlink:data[i].devlink,
                                        type:data[i].type,
                                        typename:data[i].typename,
                                        active:0
                                    }
                                    this.list.push(arr)
                                }
                            }
                        }
                    }
                })
            },
            // 关闭选择设备框
            handleClose(){
                this.dialogVisible = false
                if(this.nowshebei = '正在选择……'){
                    this.nowshebei = '不限制设备'
                    this.nowselect = {}
                    // 清除选中设备状态
                    for(var a = 0;  a < this.list.length; a++){
                        this.list[a].active = 0
                    }
                    // 清除子设备展示
                    this.specific = []
                }
            },
            // 打开选择设备框
            selectList(){
                this.dialogVisible = true
            },
            // 点击设备类型
            selectType(data){
                if(data == 'all'){
                    for(var a = 0;  a < this.list.length; a++){
                        this.list[a].active = 0
                    } 
                    this.nowselect = {}
                    this.nowshebei = '不限制设备'
                    // 清除子设备展示
                    this.specific = []
                    this.dialogVisible = false
                }else{
                    for(var a = 0;  a < this.list.length; a++){
                        if(this.list[a].type == data.type){
                            this.list[a].active = 1
                        }else{
                            this.list[a].active = 0
                        }
                    }
                    this.specific = []
                    for(var i = 0; i < data.devlink.length; i++){
                        if(data.devlink[i].ready == 1){
                            var arr = {
                                type:data.type,
                                addr:data.devlink[i].addr,
                                uid:data.devlink[i].uid,
                                typename:data.typename,
                                name:data.devlink[i].name
                            }
                            this.specific.push(arr)
                        }
                    }
                    this.nowshebei = '正在选择……'
                }
            },
            // 点击具体设备
            selectTypelink(data){
                this.nowselect = {
                    type:data.type,
                    addr:data.addr,
                    uid:data.uid
                }
                this.nowshebei = data.typename+'-'+data.name
                this.dialogVisible = false
            },
            // 搜索
            search() {
                this.getData()
            },
            getRowClass(row) {
                if (row.rowIndex % 2 == 1) {
                    return `background:rgba(58,123,255,.15) ;
                `;
                } else {
                    return `background:none ;
                `;
                }
            },
            getData() {
                var betime = 0
                if(this.afterBetime == ''){
                    betime = 0
                }else{
                    betime = this.afterBetime
                }
                if(this.afterEtime == ''){
                    this.$notify({
                        title: '请选择结束时间段',
                        type: 'warning',
                        duration: 1500
                    });
                    return false;
                }
                if(this.nowshebei == '不限制设备'){
                    var params = {
                        "geterrorhistory":{
                            "btime":betime,
                            "etime":this.afterEtime,
                            "size":this.size,
                            "page":this.page,                                                 
                        },
                        [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
                    }
                }else{
                    var params = {
                        "geterrorhistory":{
                            "btime":betime,
                            "etime":this.afterEtime,
                            "size":this.size,
                            "page":this.page,    
                            "uid":this.nowselect.uid,
                            "addr":this.nowselect.addr,
                            "type":this.nowselect.type                                             
                        },
                        [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
                    }
                }
                // console.log(params);
                this.$http.post(this.$baseUrl, params).then((res) => {
                    if(res.data.result == 'ok'){
                        this.count = res.data.count;
                        this.totalPages = Math.ceil(this.count/this.size)  //获取页码数量
                        this.currentPage = parseInt(this.page+1); // 更新页码状态
                        this.inputPage = this.currentPage; // 更新页码状态
                        this.tableData = res.data.geterrorhistory
                        for (let index = 0; index < this.tableData.length; index++) {
                            // 报警值格式修改
                            this.tableData[index].alarmvalue = this.tableData[index].id == -1 ? '':this.tableData[index].alarmvalue+' '+this.tableData[index].flag//报警值
                            this.tableData[index].ahhvalue = this.tableData[index].id == -1 ? '':this.tableData[index].ahhvalue == undefined ? '':this.tableData[index].ahhvalue//高高限
                            this.tableData[index].allvalue = this.tableData[index].id == -1 ? '':this.tableData[index].allvalue == undefined ? '':this.tableData[index].allvalue//低低限
                            // 时间格式修改
                            if(this.tableData[index].recovertime == 0){
                                this.tableData[index].recovertime = ''
                            }else{
                                this.tableData[index].recovertime = this.formatDate(this.tableData[index].recovertime* 1000,'YYYY-MM-DD H:m:s');
                            }
                            if(this.tableData[index].triggertime == 0){
                                this.tableData[index].triggertime = ''
                            }else{
                                this.tableData[index].triggertime = this.formatDate(this.tableData[index].triggertime* 1000,'YYYY-MM-DD H:m:s');
                            }
                        }
                    }
                })
            },
            // 全部导出判断
            daochu2(){
                if(this.count > 10000 || window.location.hostname == '127.0.0.1'){
                    var betime = 0
                    if(this.afterBetime == ''){
                        betime = 0
                    }else{
                        betime = this.afterBetime
                    }
                    if(this.nowshebei == '不限制设备'){
                        var params = {
                            "backuperrorhistory":{
                                "btime":betime,
                                "etime":this.afterEtime,
                            },
                            [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
                        };
                    }else{
                        var params = {
                            "geterrorhistory":{
                                "btime":betime,
                                "etime":this.afterEtime, 
                                "uid":this.nowselect.uid,                                          
                            },
                            [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
                        }
                    }
                    this.$http.post(this.$baseUrl,params).then((res)=>{
                        if(res.data.result == 'ok'){
                            if(window.location.hostname == '127.0.0.1'){//在区域控制器中
                                this.$notify({
                                    title: '正在后台自动导出中……',
                                    type: 'success',
                                    duration: 1500
                                });
                            }else{
                                this.$notify({
                                    title: '正在后台自动导出中，请到区域控制器设备中等待查看……',
                                    type: 'success',
                                    duration: 2500
                                });
                            }
                        }else{
                            this.$message({
                                message: '导出失败',
                                type: 'warning',
                                duration: 1500
                            });
                        }
                    })
                }else{
                    this.daochu()
                }
            },
            //全部导出
             daochu: async function () {
                var betime = 0
                if(this.afterBetime == ''){
                    betime = 0
                }else{
                    betime = this.afterBetime
                }
                var dataNUm  = this.count/100
                var arr = []
                for (let k = 0; k < dataNUm; k++) {
                    if(this.nowshebei == '不限制设备'){
                        var params = {
                            "geterrorhistory":{
                                "btime":betime,
                                "etime":this.afterEtime,
                                "size":this.size,
                                "page":k,                                                 
                            },
                            [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
                        }
                    }else{
                        var params = {
                            "geterrorhistory":{
                                "btime":betime,
                                "etime":this.afterEtime,
                                "size":this.size,
                                "page":k,    
                                "uid":this.nowselect.uid,
                                "addr":this.nowselect.addr,
                                "type":this.nowselect.type                                             
                            },
                            [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
                        }
                    }
                   await  this.$http.post(this.$baseUrl, params).then((res) => {
                        if(res.data.result == 'ok'){
                            for (let index = 0; index < res.data.geterrorhistory.length; index++) {
                                if(res.data.geterrorhistory[index].recovertime == 0){
                                    res.data.geterrorhistory[index].recovertime = ''
                                }else{
                                    res.data.geterrorhistory[index].recovertime = this.formatDate(res.data.geterrorhistory[index].recovertime* 1000,'YYYY-MM-DD H:m:s');
                                }
                                if(res.data.geterrorhistory[index].triggertime == 0){
                                    res.data.geterrorhistory[index].triggertime = ''
                                }else{
                                    res.data.geterrorhistory[index].triggertime = this.formatDate(res.data.geterrorhistory[index].triggertime* 1000,'YYYY-MM-DD H:m:s');
                                }
                                arr.push(res.data.geterrorhistory[index])
                            }
                        }
                    })

                }
                // console.log(arr)
                     // 导出逻辑
                require.ensure([], () => {
                    const { export_json_to_excel } = require('../../vendor/Export2Excel');
                    const tHeader = ['设备名称','单项名称','触发时间','报警信息','恢复方式','恢复时间','报警值','高高限','低低限','报警级别'];
                    const filterVal = ['devname','idname','triggertime','triggerinfo','recoverinfo','recovertime','alarmvalue','ahhvalue','allvalue','alarmlimit' ];
                    const list = arr;
                    const data = this.formatJson(filterVal, list);
                    export_json_to_excel(tHeader, data, '报警历史数据');
                })
                  
               
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]))
            },

        },
    }
</script>
<style scoped>
    .el-card {
    background: none;
    color: #fff;
    border: 1px solid rgba(89, 129, 165, 0.4);
    }
    /deep/ .el-card__header {
    background: rgba(89, 129, 165, 0.2);

    border-bottom: none;
    }
    .box-card {
    /* overflow: hidden; */
    }
    .card_padding_chart{
    padding: 7px 0;
    }
    /deep/ .el-input__inner{
        background: rgba(255, 255, 255, 0);
        border: 1px solid rgba(255, 255, 255, 0.3);
        width: 100%;
        color: #fff;
    }
    /deep/ .el-form-item__label{
        color: #fff;
    }

.shebeiDetails .el-input{
    width: 200px;
}
/deep/ .shebeiDetails .el-form-item__label{
    width: 80px;
    color: #fff;
}
/deep/ .el-dialog__title{
    color: #fff;
}
/* /deep/ .el-dialog__headerbtn .el-dialog__close{
    color: #fff;
} */
/deep/ .el-radio.is-bordered{
    color: #fff;
    margin: 10px;
    width: 120px;
}
/deep/ .el-radio{
    color: #fff;
}
 /deep/ .el-table th, /deep/  .el-table tr{
        background-color: transparent !important;
        color: #fff;
    }
    /deep/ .el-table, .el-table__expanded-cell{
        background-color: transparent !important;
    }
    /deep/ .el-table__header-wrapper{
        /* background-color: #5f7998 !important; */
        background-color: #5981a533 !important;
        border: 1px solid #475c6f;
        border-bottom: none;
    }
    /deep/ .is-scrolling-none{
        /* background: #4e6888 !important; */
            background: rgba(89,129,165,.4) !important;
    }
    /deep/ .el-table td, .el-table th.is-leaf{
        border-bottom: 1px solid #ebeef542;
        background-color: transparent !important;
    }
    /deep/ .el-table--enable-row-hover .el-table__body tr:hover>td{
        background: #4e6888;
    }
    /deep/ .el-table--striped .el-table__body tr.el-table__row--striped td {
        background: #4e6888;
    }
    /deep/ .el-table tr th.is-leaf{
        border: none;
    }
    /deep/ .el-table--border{
        border: none;
    }
     /* 清除底部横线 */
    .el-table::before {
        height: 0px;
    }
    .el-table--border::after{
        display: none;
    }
    /deep/  .el-button {
    background: rgba(89, 129, 165, 0.8);
    border: none;
}
.el-pagination{
    margin-top: 20px;
    text-align: right;
}
.warnhis_type{
    height: 200px;
    color: #fff;
    overflow-y: scroll;
    margin-bottom: 20px;
}
.warnhis_type_flex{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}
.warnhis_line{
    height: 1px;
    width: 100%;
    border: 1px dashed #ffffff8a;
    margin-bottom: 20px;
}
.warnhis_shebei{
    width: 100%;
    height: 200px;
    color: #fff;
    overflow-y: scroll;
}
.warnhis_type_but{
    margin-right: 20px;
    margin-bottom: 20px;
    border: 1px solid #ffffff8a;
    border-radius: 5px;
    cursor: pointer;
}
.warnhis_type_nomal{
    height: 50px;
    line-height: 50px;
    padding: 0px 15px;
    background: #36363614;
}
.warnhis_type_active{
    height: 50px;
    line-height: 50px;
    padding: 0px 15px;
    background: #b8e2ff29;
}
/* 页码 */
.page_wrap{
    float: right;
    padding-top: 10px;
    padding-right: 20px;
}
.page_wrap button {
  margin: 0 5px;
}
.page_wrap .active {
  font-weight: bold;
}
.yema{
    height: 28px;
    line-height: 28px;
    min-width: 30px;
    padding: 0 4px;
    border-radius: 2px;
    border:none;
    background: #fff;
    color: #606266;
    cursor: pointer;
}
.yema:disabled{
    background: #f4f4f5;
    color: #C0C4CC;
    cursor: no-drop;
}
.active{
    background: #409EFF;
    color: #FFF;
    cursor: no-drop;
}
.yema_input{
    width: 70px;
    height: 28px;
    line-height: 28px;
    padding: 0 8px;
    border-radius: 2px;
    border:1px solid #fff;
    background: none;
    color: #fff;
    text-align: right;
    transition: width 0.2s ease-in-out; /* 平滑过渡效果 */
}
</style>